package cn.stylefeng.guns.sys.modular.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.core.log.LogObjectHolder;
import cn.stylefeng.guns.sys.core.util.QiniuUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.BtyBxda;
import cn.stylefeng.guns.sys.modular.system.model.params.ProjectParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyBxdaResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyBrandService;
import cn.stylefeng.guns.sys.modular.system.service.BtyBxdaService;
import cn.stylefeng.guns.sys.modular.system.warpper.NoticeWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 报销档案控制器
 *
 * @author liuy
 * @Date
 */
@Controller
@RequestMapping("/btyBxda")
public class BtyBxdaController extends BaseController {

    private String PREFIX = "/modular/system/btyBxda/";
    @Resource
    private BtyBxdaService btyBxdaService;
    @Resource
    private BtyBrandService brandService;

    /**
     * 跳转到通知列表首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "btyBxda.html";
    }

    @RequestMapping("/zc")
    public String zc() {
        String xingming = LoginContextHolder.getContext().getUser().getName();
        String tel = LoginContextHolder.getContext().getUser().getAccount();
        btyBxdaService.initBxdaZc(tel,xingming);
        return PREFIX + "btyBxdaZc.html";
    }

    /**
     * 跳转到通知列表首页
     */
    @RequestMapping("ghs")
    public String index_ghs(Model model) {
        //当前用户
        String name = LoginContextHolder.getContext().getUser().getName();
        String tel = LoginContextHolder.getContext().getUser().getAccount();
        BtyBxdaResult bxda = btyBxdaService.getByTel("半天妖", tel);
        if (bxda == null) {
            BtyBxda mtp = new BtyBxda();
            mtp.setXm(name);
            mtp.setTel(tel);
            mtp.setDm("半天妖");
            btyBxdaService.add(mtp);

            bxda = new BtyBxdaResult();
            bxda.setId(String.valueOf(mtp.getId()));
            bxda.setTel(tel);
            bxda.setXm(name);
        }
//        if(!bxda.getXm().equals(name)){
//            BtyBxda bxdau = btyBxdaService.getById(bxda.getId());
//            bxdau.setXm(name);
//            btyBxdaService.updateById(bxdau);
//            bxda.setXm(name);
//        }
        model.addAllAttributes(BeanUtil.beanToMap(bxda));
        LogObjectHolder.me().set(bxda);
        return PREFIX + "btyBxda_edit_ghs.html";
    }

    /**
     * 跳转到通知列表首页
     */
    @RequestMapping("dgdghs")
    public String index_dgdghs(Model model) {
        //当前用户
        String name = LoginContextHolder.getContext().getUser().getName();
        String tel = LoginContextHolder.getContext().getUser().getAccount();
        BtyBxdaResult bxda = btyBxdaService.getByTel("东更道", tel);
        if (bxda == null) {
//            bxda = btyBxdaService.getByTel("半天妖", tel);
            BtyBxda mtp = new BtyBxda();
            mtp.setXm(name);
            mtp.setTel(tel);
            mtp.setDm("东更道");
            btyBxdaService.add(mtp);

            bxda = new BtyBxdaResult();
            bxda.setId(String.valueOf(mtp.getId()));
            bxda.setTel(tel);
            bxda.setXm(name);
        }
        if(!bxda.getXm().equals(name)){
            BtyBxda bxdau = btyBxdaService.getById(bxda.getId());
            bxdau.setXm(name);
            btyBxdaService.updateById(bxdau);
            bxda.setXm(name);
        }
        model.addAllAttributes(BeanUtil.beanToMap(bxda));
        LogObjectHolder.me().set(bxda);
        return PREFIX + "btyBxda_edit_dgdghs.html";
    }

    /**
     * 跳转到通知列表首页
     */
    @RequestMapping("/update_zc")
    public String index_ryxx(Model model, String id) {
        BtyBxda btyBxda = this.btyBxdaService.getById(id);
        model.addAllAttributes(BeanUtil.beanToMap(btyBxda));
        LogObjectHolder.me().set(btyBxda);
        return PREFIX + "btyBxda_edit_ryxx.html";
    }

    /**
     * 初始化报销档案
     */
    @RequestMapping(value = "/initBxda")
    @ResponseBody
    public Object initBxda() {
        String xingming = LoginContextHolder.getContext().getUser().getName();
        String tel = LoginContextHolder.getContext().getUser().getAccount();

        btyBxdaService.initBxdaZc(tel,xingming);

        return SUCCESS_TIP;
    }

    /**
     * 获取通知列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition, String ghs, String dm) {
        //获取用户的帐号
        String account = LoginContextHolder.getContext().getUser().getName();
        String username = LoginContextHolder.getContext().getUser().getAccount();
        Page<Map<String, Object>> list;
        if (account.equals("admin") | username.equals("chujunjun") | username.equals("18654546535")) {
            list = this.btyBxdaService.list(condition, null, ghs, dm);
        } else {
            list = this.btyBxdaService.list(condition, account, ghs, dm);
        }
        //Page<Map<String, Object>> list = this.btyBxdaService.list(condition);
        Page<Map<String, Object>> wrap = new NoticeWrapper(list).wrap();

        return LayuiPageFactory.createPageInfo(wrap);
    }

    /**
     * 获取通知列表
     */
    @RequestMapping(value = "/listZc")
    @ResponseBody
    public Object listZc(String condition, String ghs, String dm) {
        //获取用户的帐号
        String account = LoginContextHolder.getContext().getUser().getName();
        String username = LoginContextHolder.getContext().getUser().getAccount();
        Page<Map<String, Object>> list;
        if (account.equals("admin") | username.equals("chujunjun") | username.equals("18654546535")) {
            list = this.btyBxdaService.listZc(condition, null, dm);
        } else {
            list = this.btyBxdaService.listZc(condition, account, dm);
        }
        Page<Map<String, Object>> wrap = new NoticeWrapper(list).wrap();

        return LayuiPageFactory.createPageInfo(wrap);
    }

    /**
     * 跳转到添加档案
     */
    @RequestMapping("/btyBxda_add")
    public String noticeAdd(Model model) {
        String username = LoginContextHolder.getContext().getUser().getName();
        model.addAttribute("username", username);
        return PREFIX + "btyBxda_add.html";
    }

    /**
     * 跳转到添加档案-门店装修所用
     */
    @RequestMapping("/btyBxda_add2")
    public String noticeAddMdzxBaoXiRen(Model model) {
        String username = LoginContextHolder.getContext().getUser().getName();
        model.addAttribute("username", username);
        return PREFIX + "btyBxda_add2.html";
    }

    /**
     * 跳转到添加档案-门店装修所用 - 东更道
     */
    @RequestMapping("/btyBxda_adddgd")
    public String noticeAddMdzxBaoXiRenDgd(Model model) {
        String username = LoginContextHolder.getContext().getUser().getName();
        model.addAttribute("username", username);
        return PREFIX + "btyBxda_adddgd.html";
    }

    /**
     * 跳转到修改档案
     */
    @RequestMapping("/btyBxda_update/{id}")
    public String noticeUpdate(@PathVariable Long id, Model model) {
        BtyBxda btyBxda = this.btyBxdaService.getById(id);
        model.addAllAttributes(BeanUtil.beanToMap(btyBxda));
        LogObjectHolder.me().set(btyBxda);
        return PREFIX + "btyBxda_edit.html";
    }

    /**
     * 跳转到批量修改会计
     */
    @RequestMapping("/btyBxda_updateKj/{id}")
    public String noticeUpdateKj(@PathVariable Long id, Model model) {
        BtyBxda btyBxda = this.btyBxdaService.getById(id);
        model.addAllAttributes(BeanUtil.beanToMap(btyBxda));
        LogObjectHolder.me().set(btyBxda);
        return PREFIX + "btyBxda_editKj.html";
    }

    /**
     * 修改档案
     *
     * @author liuy
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(BtyBxda btyBxda) {
        if (ToolUtil.isOneEmpty(btyBxda, btyBxda.getId())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //替换大部分空白字符,不限于空格
        String yhk = btyBxda.getYhk().replaceAll("\\s*", "");
        //通过银行卡号获取银行简称
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(content);
        String bank;
        if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
            bank = jsonObject.get("bank").toString();
            btyBxda.setBank(bank);
            //通过银行简称获取行号
//            String code=btyBxdaService.getBankCode(bank);
//            System.out.println("code:"+code);
//            if(ToolUtil.isNotEmpty(code)){
//                if(ToolUtil.isEmpty(btyBxda.getBz())){
//                 btyBxda.setBz(code);
//                }
//            }
            //手动输入行号
        } else if (ToolUtil.isNotEmpty(btyBxda.getBz())) {
            //查询该行号对应银行简称
            Map<String, String> map = btyBxdaService.getBank(btyBxda.getBz());

            if (ToolUtil.isNotEmpty(map) && ToolUtil.isNotEmpty(map.get("ver"))) {
                btyBxda.setBank(map.get("ver"));//简称
            } else {
                btyBxda.setBank("NULL");//简称
            }


        }
        this.btyBxdaService.updateById(btyBxda);
        return SUCCESS_TIP;
    }

    /**
     * 通过银行简称识别行号
     *
     * @author liuy
     */
    @RequestMapping(value = "/bankCode")
    @ResponseBody
    public String bankCode(String bankNo) {
        String bankCode = "";
        //通过银行卡号获取银行简称
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + bankNo + "&cardBinCheck=true";
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(content);
        String bank;
        if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
            bank = jsonObject.get("bank").toString();
            //通过银行简称获取行号
            String code = btyBxdaService.getBankCode(bank);
            System.out.println("code:" + code);
            if (ToolUtil.isNotEmpty(code)) {
                bankCode = code;
            }
        }
        return bankCode;
    }

    /**
     * 批量识别银行行号
     */
    @RequestMapping(value = "/updateBz")
    @ResponseBody
    public Object updateBz() {

        //查询表中行号为空的数据
//        List<BtyBxda> list = btyBxdaService.list(new QueryWrapper<BtyBxda>().isNull("bz"));

        List<BtyBxda> list = btyBxdaService.isNullList();

        for (BtyBxda btyBxda : list) {
            String yhk = btyBxda.getYhk();//银行卡号

            //通过银行卡号获取银行简称
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
            String content = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(content);

            String bank;
            if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
                //银行简称
                bank = jsonObject.get("bank").toString();
                btyBxda.setBank(bank);

                //通过银行简称获取行号
                String code = btyBxdaService.getBankCode(bank);
                btyBxda.setBz(code);//银行行号

                //修改行号
//                btyBxdaService.updateById(btyBxda);
                btyBxdaService.updateByYhk(btyBxda);
            }
        }
        return SUCCESS_TIP;
    }


    /**
     * 批量修改会计
     *
     * @author liuy
     */
    @RequestMapping(value = "/updateKj")
    @ResponseBody
    public Object updateKj(BtyBxda btyBxda) {
        if (ToolUtil.isOneEmpty(btyBxda, btyBxda.getId())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        String kj = btyBxda.getKj();
        String dm = btyBxda.getDm();
        this.btyBxdaService.updatekj(kj, dm);
        return SUCCESS_TIP;
    }

    /**
     * 新增报销档案
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public ResponseData add(BtyBxda btyBxda) {
        if (ToolUtil.isOneEmpty(btyBxda)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        String dm = btyBxda.getDm();
        String[] dms;
        if (dm.contains(",")) {
            dms = dm.split(",");
            for (int i = 0; i < dms.length; i++) {
                btyBxda.setId(UUIDUtils.getId());
                btyBxda.setDm(dms[i]);
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String bh = df.format(new Date());
                //替换大部分空白字符,不限于空格
                String yhk = btyBxda.getYhk().replaceAll("\\s*", "");
                //通过银行卡号获取银行简称
                RestTemplate restTemplate = new RestTemplate();
                String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
                String content = restTemplate.getForObject(url, String.class);
                JSONObject jsonObject = JSONObject.parseObject(content);
                String bank;
                if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
                    bank = jsonObject.get("bank").toString();
                    btyBxda.setBank(bank);
                    //通过银行简称获取行号
                    String code = btyBxdaService.getBankCode(bank);
                    if (ToolUtil.isNotEmpty(code) && ToolUtil.isEmpty(btyBxda.getBz())) {
                        btyBxda.setBz(code);
                    }
                }


                btyBxda.setYhk(yhk);
                btyBxda.setBh(bh);
                btyBxda.setCreateUser(LoginContextHolder.getContext().getUserId());
                btyBxda.setCreateTime(new Date());
                this.btyBxdaService.save(btyBxda);
            }
        } else {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String bh = df.format(new Date());
            //替换大部分空白字符,不限于空格
            String yhk = btyBxda.getYhk().replaceAll("\\s*", "");
            //通过银行卡号获取银行简称
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
            String content = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(content);
            String bank;
            if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
                bank = jsonObject.get("bank").toString();
                btyBxda.setBank(bank);
                //通过银行简称获取行号
                String code = btyBxdaService.getBankCode(bank);
                if (ToolUtil.isNotEmpty(code) && ToolUtil.isEmpty(btyBxda.getBz())) {
                    btyBxda.setBz(code);
                }
            }
            btyBxda.setYhk(yhk);
            btyBxda.setBh(bh);
            btyBxda.setCreateUser(LoginContextHolder.getContext().getUserId());
            btyBxda.setCreateTime(new Date());
            this.btyBxdaService.save(btyBxda);
        }
        return new SuccessResponseData(btyBxda);
    }

    /**
     * 上传图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public Map<String, Object> uploads(@RequestPart("file") MultipartFile file, String packName, @RequestParam(value = "dm", required = false) String dm) {
        return QiniuUtil.uploadFile(file, dm);
    }

    /**
     * 档案详情
     */
    @RequestMapping("/info")
    @ResponseBody
    public Object getThemeInfo(@RequestParam String id) {
        if (ToolUtil.isEmpty(id)) {
            throw new RequestEmptyException();
        }
        BtyBxda btyBxda = this.btyBxdaService.getById(id);
        String account = LoginContextHolder.getContext().getUser().getAccount();
        if (account.equals("admin") | account.equals("chujunjun")) {
            btyBxda.setRoleFlag(0);
        } else {
            btyBxda.setRoleFlag(1);
        }
        return btyBxda;
    }

    /**
     * 删除报销档案
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long id) {
        this.btyBxdaService.removeById(id);
        return SUCCESS_TIP;
    }

    /**
     * 查询店名
     */
    @RequestMapping(value = "/getDm")
    @ResponseBody
    public List<BtyBxda> getDm() {
        String account = LoginContextHolder.getContext().getUser().getName();
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<BtyBxda> list;
//        if(account.equals("admin")){
//            list = this.btyBxdaService.dmList(null);
//        }else {
//            list =this.btyBxdaService.dmList(account);
//        }
        if (roleNames.contains("会计")) {
            list = this.btyBxdaService.dmList(account);
        } else {
            list = this.btyBxdaService.dmList(null);
        }
        return list;
    }


    /**
     * 门店装修需要的厂家
     *
     * @param projectParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/allVendor")
    public LayuiPageInfo getAllVendor(ProjectParam projectParam) {
        return this.btyBxdaService.getAllVendor(projectParam);
    }

    /**
     * 门店装修需要的厂家
     *
     * @param projectParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/getAllVendorList")
    public ResponseData getAllVendorList(ProjectParam projectParam) {
        return ResponseData.success(this.btyBxdaService.getAllVendorList("半天妖"));
    }

    /**
     * 门店装修需要的厂家 ID xm
     *
     * @param projectParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/getZxList")
    public ResponseData getZxList(ProjectParam projectParam) {
        return ResponseData.success(this.btyBxdaService.getZxList("半天妖"));
    }

    /**
     * 门店装修需要的厂家
     *
     * @param projectParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/getAllVendorListDgd")
    public ResponseData getAllVendorListDgd(ProjectParam projectParam) {
        return ResponseData.success(this.btyBxdaService.getAllVendorList("东更道"));
    }

    /**
     * 门店装修需要的厂家 ID xm
     *
     * @param projectParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/getZxListDgd")
    public ResponseData getZxListDgd(ProjectParam projectParam) {
        return ResponseData.success(this.btyBxdaService.getZxList("东更道"));
    }

}
